package com.bw.shiro_demo.controller;

import com.bw.shiro_demo.pojo.TUser;
import com.bw.shiro_demo.service.UserService;
import com.bw.shiro_demo.utils.MD5Utils;
import com.bw.shiro_demo.utils.R;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class LoginController {
    @Autowired
    UserService userService;
    @RequestMapping(value={"/","login"})
    public String login1(){
        return "login";
    }
//    @RequestMapping("login")
//    public String login(){
//        List<TUser> tuser = userService.selectByExample(null);
//        System.out.println(tuser);
//        return "login";
//    }

    @RequestMapping("loginSign")
    @ResponseBody
    public R loginSign(String uname, String pwd){
        //校验参数
        if(StringUtils.isBlank(uname)){
            return R.error("用户名不能为空");
        }
        if(StringUtils.isBlank(pwd)){
            return R.error("密码不能为空");
        }
        //  认证
        Subject subject = SecurityUtils.getSubject();
        //登录 认证信息
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(uname, MD5Utils.encrypt(pwd));
        try {
            subject.login(usernamePasswordToken);
        }catch (UnknownAccountException e){
            R.error("未查询到该用户");
        }catch (LockedAccountException e){
            R.error("用户认证失败");
        }catch (AuthenticationException e){
            R.error("登录失败");
        }catch (Exception e){
            R.error("登录失败");
        }
        return R.ok();
    }
    @RequestMapping("index")
    public String index(){
        return "index";
    }
    @RequestMapping("main")
    public String main(){
        return "main";
    }
}
